package com.example.demo.interceptor;

import com.example.demo.bean.User;
import com.example.demo.car.vo.UserInfo;
import com.example.demo.utils.SysUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.stream.Stream;

/**
 * 拦截器，判断用户的登录状态，并封装传递给controller目标对象
 */
@Slf4j
@Component
public class CarInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfo> threadLocal = new ThreadLocal();

    /**
     * 在目标方法执行之前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        UserInfo userInfo = new UserInfo();
        User loginUser = (User) request.getSession().getAttribute(SysUtils.LOGIN_NAME);
        if (loginUser != null) {
            // 登录
            userInfo.setUserId(loginUser.getUserId());
        }
        //    从cookie获取 user-ksy
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
           /*     Stream<Cookie> cookieStream = Arrays.stream(cookies).filter((cookie -> {
                    return cookie.getName().equals(SysUtils.TEMP_COOKIE_NAME);
                }));*/
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                log.info("cookie name={} |value={}", cookie.getName(), cookie.getValue() + "<|>" + cookie.getDomain());
                if (name.equals(SysUtils.TEMP_USER_COOKIE_NAME)) {
                    System.out.println(" car|cookie max ageis " + cookie.getMaxAge());
                    userInfo.setUserKey(cookie.getValue());
                    userInfo.setTempUser(true);
                    System.out.println(userInfo.toString());
                    break;
                }
            }
        }
        //如果没有临时用户，分配一个临时用户
        if (StringUtils.isEmpty(userInfo.getUserKey())) {
            String uuid = SysUtils.getUUID();

            // 设置在 postHandle 中 经过 ResponseBody的注解就失效了
            userInfo.setUserKey(uuid);
            Cookie cookie = new Cookie(SysUtils.TEMP_USER_COOKIE_NAME, uuid);
            cookie.setMaxAge(30 * 24 * 60 * 60);
            //子域下也可访问
            cookie.setDomain("grq.com");
            cookie.setPath("/");
            response.addCookie(cookie);
        }
        //方法执行之前
        threadLocal.set(userInfo);
        return true;
    }


    /**
     * 业务执行之后，浏览器保存cookie
     * |被@ResponseBoby注释的方法在拦截器的posthandle方法中设置cookie失效的问题|
     * https://www.cnblogs.com/insaneXs/p/7738109.html
     *
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfo userInfo = threadLocal.get();
        if (!userInfo.isTempUser()) {
            Cookie cookie = new Cookie(SysUtils.TEMP_USER_COOKIE_NAME, userInfo.getUserKey());
            cookie.setMaxAge(30 * 24 * 60 * 60);
            //子域下也可访问
            cookie.setDomain("grq.com");
            cookie.setPath("/");
            response.addCookie(cookie);
        }
    }
}

